package com.xinjian.jianba.service.impl;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.xinjian.jianba.dao.dwmid.BuziInfoDao;
import com.xinjian.jianba.dao.dwmid.BuziTypeDao;
import com.xinjian.jianba.dao.dwmid.BuziVisitDao;
import com.xinjian.jianba.dao.dwmid.BuziWorkDao;
import com.xinjian.jianba.dao.dwmid.RyGroupDao;
import com.xinjian.jianba.dao.dwmid.UserCollectBuziDao;
import com.xinjian.jianba.dao.dwmid.UserVisitBuziDao;
import com.xinjian.jianba.dto.BuziCircleDto;
import com.xinjian.jianba.dto.BuziInfoVo;
import com.xinjian.jianba.dto.BuziNameSearchDto;
import com.xinjian.jianba.dto.BuziNameSearchVo;
import com.xinjian.jianba.dto.BuziStoreIndexDto;
import com.xinjian.jianba.dto.BuziStoreIndexVo;
import com.xinjian.jianba.dto.BuziVisitCountDto;
import com.xinjian.jianba.dto.BuziWorkMediaVo;
import com.xinjian.jianba.dto.BuziWorkVo;
import com.xinjian.jianba.dto.BuziWorksDto;
import com.xinjian.jianba.dto.CollectBuziDto;
import com.xinjian.jianba.dto.CollectListDto;
import com.xinjian.jianba.dto.CollectListVo;
import com.xinjian.jianba.dto.GroupDto;
import com.xinjian.jianba.dto.es.EsServiceResult;
import com.xinjian.jianba.enity.BuziInfoEntity;
import com.xinjian.jianba.enity.BuziTypeEntity;
import com.xinjian.jianba.enity.BuziVisitEntity;
import com.xinjian.jianba.enity.BuziWorkEntity;
import com.xinjian.jianba.enity.BuziWorkMediaEntity;
import com.xinjian.jianba.enity.RyGroupEntity;
import com.xinjian.jianba.enity.UserCollectBuziEntity;
import com.xinjian.jianba.exception.BusinessException;
import com.xinjian.jianba.exception.ResponseCode;
import com.xinjian.jianba.service.BuziVisitService;
import com.xinjian.jianba.service.EsService;

import com.xinjian.jianba.utils.Constants;
import com.xinjian.jianba.utils.DateUtil;
import com.xinjian.jianba.utils.EsUtil;
@Service
public class BuziVisitServiceImpl implements BuziVisitService{

	@Autowired
	private BuziVisitDao buziVisitDao;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@Autowired
	private EsService esService;
	@Autowired
	private BuziWorkDao buziWorkDao;
	@Autowired
	private BuziInfoDao buziInfoDao;
	@Autowired
	private BuziTypeDao buziTypeDao;
	@Autowired
	private RyGroupDao ryGroupDao;
	@Autowired
	private UserVisitBuziDao userVisitBuziDao;
	@Autowired
	private UserCollectBuziDao userCollectBuziDao;
	@Value("${jianba.business.buziLogo}")
	private String buziLogo;
//	@Override
//	public int updateBuziVisitCount(BuziVisitCountDto buziVisitCountDto) throws ParseException {
//		BuziVisitEntity buziVisitEntity=new BuziVisitEntity();
//		buziVisitEntity.setAddtime(new Timestamp(new Date().getTime()));
//		buziVisitEntity.setBuziId(buziVisitCountDto.getBuziId());
//		buziVisitEntity.setAdddate(new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse(buziVisitCountDto.getDate()).getTime()));//redis里凌晨同步的昨天的访客数据
//		buziVisitEntity.setCount(Long.parseLong(buziVisitCountDto.getCount()));
//		buziVisitDao.updateCount(buziVisitEntity);
//		return 1;
//	}
	@Override
	public void incrCount(Long buziId) {
		String key=Constants.BUZI_VISIT+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"_"+buziId;
		stringRedisTemplate.opsForValue().setIfAbsent(key, "0");
		stringRedisTemplate.opsForValue().increment(key, 1);
	}
	@Override
	public int insertBuziVisitCount(BuziVisitCountDto buziVisitCountDto) throws ParseException {
		BuziVisitEntity buziVisitEntity=new BuziVisitEntity();
		buziVisitEntity.setAddtime(new Timestamp(new Date().getTime()));
		buziVisitEntity.setBuziId(buziVisitCountDto.getBuziId());
		buziVisitEntity.setAdddate(new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse(buziVisitCountDto.getDate()).getTime()));//redis里凌晨同步的昨天的访客数据
		buziVisitEntity.setCount(Long.parseLong(buziVisitCountDto.getCount()));
		buziVisitDao.insert(buziVisitEntity);
		return 1;
	}
	@Override
	public List<BuziNameSearchVo> buziNameSearch(BuziNameSearchDto buziNameSearchDto) throws IOException {
		QueryBuilder queryBuilder=null;
		if(!StringUtils.isBlank(buziNameSearchDto.getBuziName())){
			queryBuilder=QueryBuilders.matchPhraseQuery(EsUtil.buziInfoNAME, buziNameSearchDto.getBuziName().trim());
		}
       EsServiceResult esServiceResult=esService.find(EsUtil.buziInfoIndex, EsUtil.buziInfoKeyType, queryBuilder, buziNameSearchDto.getLngfloat(), buziNameSearchDto.getLatfloat(), buziNameSearchDto.getPageNumber(), buziNameSearchDto.getPageSize());
       List<BuziNameSearchVo> listResult=new ArrayList<BuziNameSearchVo>();
       List<BuziNameSearchVo> listWorkNUll=new ArrayList<BuziNameSearchVo>();
       List<Map<String,Object>> list=null;
       if(esServiceResult.getStatus()==EsServiceResult.ResultStatus.NOT_FOUND.getValue()){
    	   return null;
	   }else if(esServiceResult.getStatus()==EsServiceResult.ResultStatus.SUCCESS.getValue()){
		   list=esServiceResult.getList();
		   list.stream().forEach(buziInfoMap ->{
			   String buziId=buziInfoMap.get(EsUtil.buziInfoBUZIID).toString();
			   buziInfoMap.remove(EsUtil.buziInfoUP_TIME);
			   buziInfoMap.remove(EsUtil.buziInfoLOCATION);
			   String type=buziInfoMap.get(EsUtil.buziInfoTYPE).toString();
			   BuziTypeEntity buziTypeEntity=buziTypeDao.getBuziTypesByType(Long.parseLong(type));
			   buziInfoMap.put(EsUtil.buziInfoTYPE, buziTypeEntity.getTypename());
			   BuziWorksDto buziWorksDto =new BuziWorksDto();
			   buziWorksDto.setBuziId(Long.parseLong(buziId));
			   buziWorksDto.setPageNumber(1);
			   buziWorksDto.setPageSize(1);
			   List<BuziWorkEntity> listWork=buziWorkDao.getBuziWorks(buziWorksDto);
			   BuziWorkVo buziWorkVo=null;
			   if(!CollectionUtils.isEmpty(listWork)){
					BuziWorkEntity buziWork=listWork.get(0);
					List<BuziWorkMediaEntity> list2=buziWork.getList();
					List<BuziWorkMediaVo> list3=new ArrayList<BuziWorkMediaVo>();
					list2.stream().forEach(buziWorkMediaEntity->{
						BuziWorkMediaVo buziWorkMediaVo=new BuziWorkMediaVo();
						buziWorkMediaVo.setWork_image(buziWorkMediaEntity.getWork_image());
						list3.add(buziWorkMediaVo);
					});
					buziWorkVo=new BuziWorkVo();
					buziWorkVo.setContent(buziWork.getContent());
					buziWorkVo.setEnd(DateUtil.utilDateToString(buziWork.getEnd()));
					buziWorkVo.setWorkId(buziWork.getId());
					buziWorkVo.setList(list3);
					buziWorkVo.setStart(DateUtil.utilDateToString(buziWork.getStart()));
					buziWorkVo.setTheme(buziWork.getTheme());
			   }
			   BuziNameSearchVo buziNameSearchVo=new BuziNameSearchVo();
			   if(buziWorkVo==null){
				   buziNameSearchVo.setBuziInfo(buziInfoMap);
				   buziNameSearchVo.setBuziWorkVo(new BuziWorkVo());
				   listWorkNUll.add(buziNameSearchVo);
			   }else {
				   buziNameSearchVo.setBuziInfo(buziInfoMap);
				   buziNameSearchVo.setBuziWorkVo(buziWorkVo);
				   listResult.add(buziNameSearchVo);//活动非空的
			   }
		   });
		   listResult.addAll(listWorkNUll);
		   return listResult;
	   }else{
		   throw new BusinessException(ResponseCode.ERROR,ResponseCode.ERROR_MSG);
	   }
	}
	@Override
	public BuziStoreIndexVo buziStoreIndex(BuziStoreIndexDto buziStoreIndexDto) {
		BuziInfoEntity buziInfoEntity=new BuziInfoEntity();
		buziInfoEntity.setId(Long.parseLong(buziStoreIndexDto.getBuziId()));
		List<BuziInfoEntity> list=buziInfoDao.select(buziInfoEntity);
		if(CollectionUtils.isEmpty(list)){
			throw new BusinessException(ResponseCode.ERROR, "不存在该商家");
		}
		//引流数加1
		incrCount(Long.parseLong(buziStoreIndexDto.getBuziId()));
		
		//记录店铺访客记录
		userVisitBuziDao.watchBuziHistory(buziStoreIndexDto);
		
		//查看是否收藏过店铺 0:没有  1:有
		Map<String, Long> map=userCollectBuziDao.selectByUserIdAndBuziId(buziStoreIndexDto);
		Long isCollect=map.get("isCollect");
		String collectId=null;
		if(isCollect.equals(0)){
			collectId="";
		}else{
			collectId=String.valueOf(map.get("collectId"));
		}
		//组装返回结果
		BuziInfoEntity buziInfo=list.get(0);
		BuziInfoVo buziInfoVo=new BuziInfoVo();
		buziInfoVo.setAddress(buziInfo.getAddress());
		buziInfoVo.setArea(buziInfo.getArea());
		buziInfoVo.setBuziId(String.valueOf(buziInfo.getId()));
		buziInfoVo.setCity(buziInfo.getCity());
		buziInfoVo.setLinkman(buziInfo.getLinkman());
		buziInfoVo.setLogo(buziInfo.getLogo());
		buziInfoVo.setName(buziInfo.getName());
		buziInfoVo.setPhone(buziInfo.getPhone());
		buziInfoVo.setProvince(buziInfo.getProvince());
		buziInfoVo.setIsCollect(String.valueOf(isCollect));
		buziInfoVo.setCollectId(collectId);
		if(buziInfo.getType()==null){
			throw new BusinessException(ResponseCode.ERROR, "该商家资料未认证");//商家还未填写个人资料
		}
		BuziTypeEntity buziTypeEntity=buziTypeDao.getBuziTypesByType(buziInfo.getType().longValue());
		buziInfoVo.setType(buziTypeEntity.getTypename());
		
		BuziWorksDto buziWorksDto=new BuziWorksDto();
		buziWorksDto.setBuziId(Long.parseLong(buziStoreIndexDto.getBuziId()));
		buziWorksDto.setPageNumber(buziStoreIndexDto.getPageNumber());
		buziWorksDto.setPageSize(buziStoreIndexDto.getPageSize());
		List<BuziWorkEntity> workList=buziWorkDao.getBuziWorks(buziWorksDto);
		List<BuziWorkVo> listBuziWorkVo=new ArrayList<BuziWorkVo>();
		workList.stream().forEach(buziWork->{
			List<BuziWorkMediaEntity> list2=buziWork.getList();
			List<BuziWorkMediaVo> list3=new ArrayList<BuziWorkMediaVo>();
			list2.stream().forEach(buziWorkMediaEntity->{
				BuziWorkMediaVo buziWorkMediaVo=new BuziWorkMediaVo();
				buziWorkMediaVo.setWork_image(buziWorkMediaEntity.getWork_image());
				list3.add(buziWorkMediaVo);
			});
			BuziWorkVo buziWorkVo=new BuziWorkVo();
			buziWorkVo.setContent(buziWork.getContent());
			buziWorkVo.setEnd(DateUtil.utilDateToString(buziWork.getEnd()));
			buziWorkVo.setWorkId(buziWork.getId());
			buziWorkVo.setList(list3);
			buziWorkVo.setStart(DateUtil.utilDateToString(buziWork.getStart()));
			buziWorkVo.setTheme(buziWork.getTheme());
			listBuziWorkVo.add(buziWorkVo);
	   });
		List<RyGroupEntity> ryList=ryGroupDao.selectGroupsByCreatorId(buziInfoVo.getBuziId()+"b");
		List<GroupDto> groupList=new ArrayList<GroupDto>();
		ryList.stream().forEach(ryGroupEntity->{
			GroupDto groupDto=new GroupDto();
			groupDto.setGroupId(ryGroupEntity.getGroupId());
			groupDto.setGroupName(ryGroupEntity.getGroupName());
			groupList.add(groupDto);
		});
		buziInfoVo.setGroups(groupList);
		BuziStoreIndexVo buziStoreIndexVo=new BuziStoreIndexVo();
		buziStoreIndexVo.setBuziInfoVo(buziInfoVo);
		buziStoreIndexVo.setList(listBuziWorkVo);
		return buziStoreIndexVo;
	}
	@Override
	public List<BuziNameSearchVo> buziCircle(BuziCircleDto buziCircleDto) {
	       EsServiceResult esServiceResult=esService.find(EsUtil.buziInfoIndex, EsUtil.buziInfoKeyType, null, buziCircleDto.getLngfloat(), buziCircleDto.getLatfloat(), buziCircleDto.getPageNumber(), buziCircleDto.getPageSize());
	       List<BuziNameSearchVo> listResult=new ArrayList<BuziNameSearchVo>();
	       List<BuziNameSearchVo> listWorkNUll=new ArrayList<BuziNameSearchVo>();
	       List<Map<String,Object>> list=null;
	       if(esServiceResult.getStatus()==EsServiceResult.ResultStatus.NOT_FOUND.getValue()){
	    	   return null;
		   }else if(esServiceResult.getStatus()==EsServiceResult.ResultStatus.SUCCESS.getValue()){
			   list=esServiceResult.getList();
			   list.stream().forEach(buziInfoMap ->{
				   String buziId=buziInfoMap.get(EsUtil.buziInfoBUZIID).toString();
				   buziInfoMap.remove(EsUtil.buziInfoUP_TIME);
				   buziInfoMap.remove(EsUtil.buziInfoLOCATION);
				   String type=buziInfoMap.get(EsUtil.buziInfoTYPE).toString();
				   BuziTypeEntity buziTypeEntity=buziTypeDao.getBuziTypesByType(Long.parseLong(type));
				   buziInfoMap.put(EsUtil.buziInfoTYPE, buziTypeEntity.getTypename());
				   BuziWorksDto buziWorksDto =new BuziWorksDto();
				   buziWorksDto.setBuziId(Long.parseLong(buziId));
				   buziWorksDto.setPageNumber(1);
				   buziWorksDto.setPageSize(1);
				   List<BuziWorkEntity> listWork=buziWorkDao.getBuziWorks(buziWorksDto);
				   BuziWorkVo buziWorkVo=null;
				   if(!CollectionUtils.isEmpty(listWork)){
						BuziWorkEntity buziWork=listWork.get(0);
						List<BuziWorkMediaEntity> list2=buziWork.getList();
						List<BuziWorkMediaVo> list3=new ArrayList<BuziWorkMediaVo>();
						list2.stream().forEach(buziWorkMediaEntity->{
							BuziWorkMediaVo buziWorkMediaVo=new BuziWorkMediaVo();
							buziWorkMediaVo.setWork_image(buziWorkMediaEntity.getWork_image());
							list3.add(buziWorkMediaVo);
						});
						buziWorkVo=new BuziWorkVo();
						buziWorkVo.setContent(buziWork.getContent());
						buziWorkVo.setEnd(DateUtil.utilDateToString(buziWork.getEnd()));
						buziWorkVo.setWorkId(buziWork.getId());
						buziWorkVo.setList(list3);
						buziWorkVo.setStart(DateUtil.utilDateToString(buziWork.getStart()));
						buziWorkVo.setTheme(buziWork.getTheme());
				   }
				   BuziNameSearchVo buziNameSearchVo=new BuziNameSearchVo();
				   if(buziWorkVo==null){
					   buziNameSearchVo.setBuziInfo(buziInfoMap);
					   buziNameSearchVo.setBuziWorkVo(new BuziWorkVo());
					   listWorkNUll.add(buziNameSearchVo);
				   }else {
					   buziNameSearchVo.setBuziInfo(buziInfoMap);
					   buziNameSearchVo.setBuziWorkVo(buziWorkVo);
					   listResult.add(buziNameSearchVo);//活动非空的
				   }
			   });
			   listResult.addAll(listWorkNUll);
			   return listResult;
		   }else{
			   throw new BusinessException(ResponseCode.ERROR,ResponseCode.ERROR_MSG);
		   }
	}
	@Override
	public BuziWorkVo findWorkDetai(Long workId) {
		BuziWorkEntity buziWorkEntity=buziWorkDao.getBuziWorkDetais(workId);
		List<BuziWorkMediaEntity> list2=buziWorkEntity.getList();
		List<BuziWorkMediaVo> list3=new ArrayList<BuziWorkMediaVo>();
		list2.stream().forEach(buziWorkMediaEntity->{
			BuziWorkMediaVo buziWorkMediaVo=new BuziWorkMediaVo();
			buziWorkMediaVo.setWork_image(buziWorkMediaEntity.getWork_image());
			list3.add(buziWorkMediaVo);
		});
		BuziWorkVo buziWorkVo=new BuziWorkVo();
		buziWorkVo.setContent(buziWorkEntity.getContent());
		buziWorkVo.setEnd(DateUtil.utilDateToString(buziWorkEntity.getEnd()));
		buziWorkVo.setWorkId(buziWorkEntity.getId());
		buziWorkVo.setList(list3);
		buziWorkVo.setStart(DateUtil.utilDateToString(buziWorkEntity.getStart()));
		buziWorkVo.setTheme(buziWorkEntity.getTheme());
		buziWorkVo.setCreateTime(DateUtil.utilDateToString(buziWorkEntity.getAdddate()));
		BuziInfoEntity buziInfoEntity=new BuziInfoEntity();
		buziInfoEntity.setId(buziWorkEntity.getBuziId());
		List<BuziInfoEntity> buziInfoList=buziInfoDao.select(buziInfoEntity);
		if(!CollectionUtils.isEmpty(buziInfoList)){
			BuziInfoEntity buziInfo=buziInfoList.get(0);
			buziWorkVo.setBuziName(buziInfo.getName());
		}else{
			buziWorkVo.setBuziName("");
		}
		return buziWorkVo;
	}
	@Override
	public Long collectBuzi(CollectBuziDto collectBuziDto) {
		Date date=new Date();
		UserCollectBuziEntity userCollectBuziEntity=new UserCollectBuziEntity();
		userCollectBuziEntity.setAddDate(date);
		userCollectBuziEntity.setAddTime(date);
		userCollectBuziEntity.setBuziId(collectBuziDto.getBuziId());
		userCollectBuziEntity.setUserId(collectBuziDto.getUserId());
		try{
		userCollectBuziDao.insertSelective(userCollectBuziEntity);
		}catch(DuplicateKeyException e){
			throw new BusinessException(ResponseCode.ERROR, "已收藏该店铺");
		}
		Long collectId=userCollectBuziEntity.getId();
		return collectId;
	}
	@Override
	public void cancleCollectBuzi(String collectId) {
		int count=userCollectBuziDao.deleteByPrimaryKey(Long.parseLong(collectId));
		if(count==0){
			throw new BusinessException(ResponseCode.ERROR, "您已取消收藏");
		}
	}
	@Override
	public List<CollectListVo> buziVisitService(CollectListDto collectListDto) {
		List<CollectListVo> list=userCollectBuziDao.collectList(collectListDto);
		list.stream().forEach(collectListVo->{
			if(StringUtils.isBlank(collectListVo.getBuziLogo())){
				collectListVo.setBuziLogo(buziLogo);
			}
			if(StringUtils.isBlank(collectListVo.getBuziName())){
				collectListVo.setBuziName(RongYunGroupServiceImpl.buziname);
			}
		});
		return list;
	}

}
